package com.cskaoyan.controller.admin;

import com.cskaoyan.bean.*;
import com.cskaoyan.bean.common.BaseRespVo;
import com.cskaoyan.config.realm.MarketToken;
import com.cskaoyan.mapper.MarketAdminMapper;
import com.cskaoyan.service.admin.AuthService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.servlet.ShiroHttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

//shiro整合之后，在做具体的开发
//响应结果都是JSON，Controller组件上我们都用@RestController注解
//@RestController
//@RequestMapping("admin/auth")
//public class AuthController {
//
//    @Autowired
//    MarketAdminMapper adminMapper;
//
//    /**
//     * Shiro安全框架 → 视频课程 4个课时 → 认证（登录）
//     * 如果参数比较少，类型比较简单的话，使用map来接收也可以
//     */
//    @RequiresPermissions("aaa")
//    @PostMapping("login")
//    public BaseRespVo<LoginUserData> login(@RequestBody Map map) {
//        String username = (String) map.get("username");
//        String password = (String) map.get("password");
//
//        // 写业务
//        //在这里要执行登录，Subject.login
//        // → Subject只能作为局部变量，不能作为全局变量
//        Subject subject = SecurityUtils.getSubject();
//        // 执行登录（认证）
//        // UsernamePasswordToken authenticationToken = new UsernamePasswordToken(username,password);
//        MarketToken authenticationToken = new MarketToken(username, password, "admin");
//        try {
//            // realm.doGetAuthenticationInfo
//            subject.login(authenticationToken);
//        } catch (AuthenticationException e) {
//            e.printStackTrace();
//            return BaseRespVo.erroPassword();
//        }
//
//        // 判断是否认证成功
//        boolean authenticated = subject.isAuthenticated();
//        // 可以获得session信息，也可以获得其sessionId
//        Session session = subject.getSession();
//        if (authenticated) {
//            // 认证成功
//            MarketAdminExample example = new MarketAdminExample();
//            MarketAdminExample.Criteria criteria = example.createCriteria();
//            criteria.andUsernameEqualTo(username);
//            List<MarketAdmin> adminList = adminMapper.selectByExample(example);
//            for (MarketAdmin marketAdmin : adminList) {
//                session.setAttribute("admin", marketAdmin);
//            }
//        }
//
//        // 获得Principal信息 → realm的doGetAuthorizationInfo方法构造的认证信息里的第一个参数
//        // MarketAdmin primaryPrincipal = (MarketAdmin) subject.getPrincipals().getPrimaryPrincipal();
//
//        LoginUserData loginUserData = new LoginUserData();
//        AdminInfoBean adminInfo = new AdminInfoBean();
//        MarketAdmin admin = (MarketAdmin) session.getAttribute("admin");
//        // adminInfo.setAvatar("https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif");
//        adminInfo.setAvatar(admin.getAvatar());
//        // adminInfo.setNickName("admin123");
//        adminInfo.setNickName(admin.getUsername());
//        loginUserData.setAdminInfo(adminInfo);
//        // loginUserData.setToken("c4d988f3-e4c5-4e46-b6ce-13b9e008ea20");
//        loginUserData.setToken((String) session.getId());
//        return BaseRespVo.ok(loginUserData);
//    }
//
//
//    @RequestMapping("info")
//    public BaseRespVo info(String token) {
//
//        //开发完shiro之后，再整合
//        InfoData infoData = new InfoData();
//        infoData.setName("admin123");
//
//        //根据primaryPrincipal做查询
//        infoData.setAvatar("https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif");
//        ArrayList<String> roles = new ArrayList<>();
//        roles.add("超级管理员");
//        infoData.setRoles(roles);
//        ArrayList<String> perms = new ArrayList<>();
//        perms.add("*");
//        infoData.setPerms(perms);
//
//        return BaseRespVo.ok(infoData);
//    }
//
//    @PostMapping("logout")
//    public BaseRespVo logout() {
//
//        return BaseRespVo.ok();
//    }
//
//}
@RestController
@RequestMapping("/admin/auth")
public class AuthController {

    @Autowired
    AuthService authService;

    /**
     * Shiro
     * 如果参数比较少，类型比较简单的话，使用map来接收也可以
     */
    @PostMapping("login")
    public BaseRespVo<LoginUserData> login(@RequestBody Map map) throws Exception{
        String username = (String)map.get("username");
        String password = (String)map.get("password");

        LoginUserData loginUserData = authService.login(username, password);
        if(loginUserData==null){
            return BaseRespVo.error(-1,"登录失败，请检查用户名与密码是否正确");
        }
        return BaseRespVo.ok(loginUserData);
    }



    @RequestMapping("info")
    public BaseRespVo info(String token) {
        //开发完shiro之后，再整合


        InfoData infoData = authService.getInfo(token);


        return BaseRespVo.ok(infoData);
    }

    @RequestMapping("/logout")
    public BaseRespVo logout(){
        Subject subject = SecurityUtils.getSubject();
        if (subject.isAuthenticated()) {
            subject.logout();
        }
        return BaseRespVo.ok();
    }

    @RequestMapping("/noAuthc")
    public BaseRespVo noAuthc(HttpServletRequest request) throws IOException {
        //response.sendRedirect("http://localhost:9527/");
        request.setAttribute(ShiroHttpServletRequest.SESSION_ID_URL_REWRITING_ENABLED, false);
        return BaseRespVo.error(501,"没有权限");
    }

}





